package com.itheima.contorller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.domian.Employees;
import com.itheima.domian.MyPage;
import com.itheima.domian.vo.EmployeeVo;
import com.itheima.mapper.admin.EmployeeMapper;
import com.itheima.service.impl.EmployeeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author 12441
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployController {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private EmployeeServiceImpl employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @PostMapping("/login")
    public R<Employees> login(@RequestBody Employees employees) {
        //根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employees> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employees::getUsername, employees.getUsername()).eq(Employees::getPassword, employees.getPassword());
        Employees emp = employeeService.getOne(queryWrapper);


        if (employees == null) {

            return R.error("登录失败,用户名或者密码错误！");

        }
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //token条件：唯一、需要加密、识别用户
        String tokenString = System.currentTimeMillis() + employees.getId();
        //加密token
        String token = String.valueOf(DigestUtils.md5Digest(tokenString.getBytes(StandardCharsets.UTF_8)));

        String jsonString = JSON.toJSONString(emp);
        //将token存入Redis
        redisTemplate.opsForValue().set(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token,jsonString,
                20, TimeUnit.MINUTES);

        EmployeeVo employeeVo = new EmployeeVo();
        employeeVo.setToken(token);
        BeanUtils.copyProperties(emp, employeeVo);
        return R.success(employeeVo,"登录成功！");
    }

    @PostMapping("/logout")
    public R<String> logout(@RequestHeader("Authorization") String token) {


        //删除token
        redisTemplate.delete(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token);

        //显示给前端的
        return R.success("退出成功");
    }
    @GetMapping("/page")
    public R<MyPage> page(HttpServletRequest httpServerRequest){

        MyPage myPage = new MyPage();

        String name = httpServerRequest.getParameter("name");
        Integer page = Integer.valueOf(httpServerRequest.getParameter("page"));
        Integer size = Integer.valueOf(httpServerRequest.getParameter("pageSize"));


        IPage ipage=new Page(page,size);

        employeeMapper.selectPage(ipage,null);

        //查询数据ipage.getRecords();
        long total = ipage.getTotal();
        if (total==0){

            return R.error("无数据");
        }
        myPage.setRecords(ipage.getRecords());
        myPage.setTotal(ipage.getTotal());
        myPage.setSize(size);
        myPage.setCurrent(page);
        return R.success(myPage,"查询完成");

    }

    @GetMapping("/{id}")
    public R<Employees> selectById(@PathVariable int id ) {

        //根据页面提交的用户名username查询数据库
        Employees employees = employeeMapper.selectById(id);

        return R.success(employees,"登录成功！");
    }
    @PostMapping
    public R<String> addUser(@RequestBody Employees employees) {
        //初始化新用户密码
        employees.setPassword("1234");


        String sex = employees.getSex();
        if (sex.equals("1")){
            employees.setSex("男");
        }
        else {
            employees.setSex("女");
        }

        employeeMapper.addUser(employees);

        return R.success("退出成功");
    }

    @PutMapping
    public R<Employees> update(@RequestBody Employees employees){
        Integer status = employees.getStatus();
        log.info("----------"+ status);
        if (status==0){
            status=0;
        }
        else {
            status=1;
        }
        employees.setStatus(status);
        employeeMapper.updateById(employees);
       return R.success(employees,"修改成功");
    }

    }


